package com.woniuxy.usercoachassemble.controller;

import com.woniuxy.usercoachassemble.commons.*;
import com.woniuxy.usercoachassemble.entity.User;
import com.woniuxy.usercoachassemble.service.UserService;
import com.woniuxy.usercoachassemble.service.YogaGymInfoService;
import org.example.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: LoginCtroller
 * Description: 用户登录控制层
 * date: 2020/7/10 15:29
 *
 * @author Fy浪迹、
 */
@RequestMapping("login")
@RestController
public class LoginCtroller {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private YogaGymInfoService yogaGymInfoService;

    /**
     * @description:TODO(通过密码登录)
     * @param loginField 用户名/电话/邮箱
     * @param password   密码
     * @return:  org.example.Result
     * @author: Fy浪迹、
     * @date: 2020/7/13 15:12
     */
    @PostMapping("loginByPassword")
    public Result loginByPassword(String loginField,String password){
        System.out.println(loginField+":"+password);
        // 校验参数
        if (ValidatorUtils.isNullOrEmpty(loginField) || ValidatorUtils.isNullOrEmpty(password)){
            return Result.Error(600,"传入参数不能为空！");
        }




        // 图形验证码
/*        String yzmCode = (String)request.getAttribute(ConstantPool.IMG_YZM_CODE);
        // 判断code是否失效
        if(ValidatorUtils.isNullOrEmpty(yzmCode)){
            return Result.Error(600,"验证码已失效");
        }
        // 判断验证码是否正确
        if(!code.equals(yzmCode)){
            return  Result.Error(600,"验证码错误");
        }*/
        // 登录是否成功
        Boolean flag = null;
        User user  = null;
        // 判断loginField 类型
        // 是否为手机号格式
        if (ValidatorUtils.isMobile(loginField)){
            user = userService.selectUserByTel(loginField);
            System.out.println(user);
            if (user != null && password.equals(user.getPassword())){
                flag = true;
            }else {
                flag = false;
            }
        }

        // 是否为邮箱格式
        if (ValidatorUtils.isEmail(loginField)){
            user = userService.selectUserByEmail(loginField);

            if (user != null && password.equals(user.getPassword())){
                flag = true;
            }else {
                flag = false;
            }


        }

        // 是否为用户名格式
        if(ValidatorUtils.isUsername(loginField)){
            user = userService.selectUserByUsername(loginField);

            if (user != null && password.equals(user.getPassword())){
                flag = true;

            }else {
                flag = false;
            }
        }




        if(flag == null){
            return Result.Error(600,"账号格式错误!");
        }

        if(flag == false || user == null){
            return Result.Error(600,"用户名或密码错误!");
        }


        if(user.getStatus() == 1){
            return Result.Error(600,"该账号尚未激活!");
        }

        if(user.getStatus() == 3){
            return Result.Error(600,"该账号已被封禁!");
        }






        if(flag == true){
            user.setPassword(null);

            Result result = Result.Success(user);
            result.setMessage("登录成功");


            return result;
        }

        return  Result.Error(600,"用户名或密码错误");


    }
    /**
     * @description:TODO(根据手机验证码登录)
     * @param tel  手机号
     * @param code  验证码
     * @return:  org.example.Result
     * @author: Fy浪迹、
     * @date: 2020/7/13 15:53
     */
    @PostMapping("loginByTelCode")
    public Result loginByTelCode(String tel,String code){
        // 参数校验
        if(ValidatorUtils.isNullOrEmpty(tel) || ValidatorUtils.isNullOrEmpty(code)){
            return Result.Error(600,"参数不能为空!");
        }

        // 判断tel是否存在
        User user = userService.selectUserByTel(tel);
        if(user == null){
            return Result.Error(600,"电话号码不存在!");
        }


        // 判断验证码是否正确
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String telCode = opsForValue.get(ConstantPool.TEL_LOGIN_CODE_PREFIX + tel);
        if(ValidatorUtils.isNullOrEmpty(telCode)){
            return Result.Error(600,"验证码已失效");
        }



        if(user.getStatus() == 1){
            return Result.Error(600,"该账号尚未激活!");
        }

        if(user.getStatus() == 3){
            return Result.Error(600,"该账号已被封禁!");
        }

        if(telCode.equals(code)){
            User user1 = user.setPassword(null);
            Result success = Result.Success(user1);
            success.setMessage("登录成功");
            // 清除redis 手机验证码缓存
            redisTemplate.delete(ConstantPool.TEL_LOGIN_CODE_PREFIX);
            return success;
        }

        return Result.Error(600,"验证码错误");




    }


    /**
     * @description:TODO(发送手机登录验证码)
     * @param tel
     * @return:  org.example.Result
     * @author: Fy浪迹、
     * @date: 2020/7/13 15:55
     */
    @PostMapping("getLoginCode")
    public Result getLoginCode(String tel){

        // 校验电话号码格式是否正确
        if(tel == null || tel.isEmpty() || !ValidatorUtils.isMobile(tel)){
            return Result.Error(600,"电话格式错误");
        }

        // 判断电话号码是否存在
        User userRegister = userService.selectUserByTel(tel);
        if(userRegister == null){
            return Result.Error(600,"该电话号码不存在");
        }

        // 随机生成6位数code
        String code = RandomUtils.get6PlaceNum() + "";
        System.out.println("手机登录验证码"+code);
        // 发送短信 电话号码,发送模板:注册,验证码
        boolean b = SMSUtils.sendSMS(tel, SMSUtils.TEMPLATECODE_LOGIN, code);
//        boolean b = true;
        if(!b){
            return Result.Error(600,"发送失败");
        }

        // 将手机号code 存入redis
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(ConstantPool.TEL_LOGIN_CODE_PREFIX+tel,code,3, TimeUnit.MINUTES);
        Result success = Result.Success();
        success.setMessage("验证码已发送");
        return success;
    }



    /**
     * @description:TODO(生成图形验证码)
     * @param loginField
     * @param request
     * @param response
     * @return:  void
     * @author: Fy浪迹、
     * @date: 2020/7/13 14:47
     */
    @RequestMapping("createImgYZM")
    public void createImgYZM(String loginField,HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        // 创建验证码并保存在session中
        YZMUtils.createCode(request,response);
    }

}
